/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

// import { Alert, Button } from 'antd';
import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import {
  MULTI_SOLUTION_SCHEMA,
  MultiSolutionWidget,
} from '@app-cad/common/components/command-form/widgets/multi-solution';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { omitBy } from 'lodash';
import { useEffect, useMemo, useState } from 'react';
import { ChildLinearSweepCommandProps } from './types';

type FormData = {
  surface1?: pickedFaceData;
  surface2?: pickedFaceData;
  spline?: pickedLineData;
  leftBound?: pickedVertexData;
  rightBound?: pickedVertexData;
};

type Params = {
  mode: 'TwoTangencySurfaces';
  surface1: string;
  surface2: string;
  spline?: {
    id?: string;
    leftBound?: string;
    rightBound?: string;
  };
  solution: number;
};

export function TwoTangencySurfaces({
  onClose,
  editDxid,
  props,
}: ChildLinearSweepCommandProps) {
  const initData: FormData = {
    surface1: null,
    surface2: null,
    spline: null,
    leftBound: null,
    rightBound: null,
  };
  const [formData, setFormData] = useState<FormData>(initData);

  const [solutionNum, setSolutionNum] = useState(0);
  const [solution, setSolution] = useState(0);

  const schema: RJSFSchema = useMemo(() => {
    const properties = omitBy(
      {
        surface1: {
          type: 'string',
          format: PickInputRJSFFormat.PickSurface,
        },
        surface2: {
          type: 'string',
          format: PickInputRJSFFormat.PickSurface,
        },
        spline: {
          type: 'string',
          format: PickInputRJSFFormat.PickCurve,
        },
        leftBound: {
          type: 'string',
          format: PickInputRJSFFormat.PickVertexAndFace,
        },
        rightBound: {
          type: 'string',
          format: PickInputRJSFFormat.PickVertexAndFace,
        },
        solution: MULTI_SOLUTION_SCHEMA,
      },
      (val) => val == null,
    );

    return {
      type: 'object',
      properties,
    } as RJSFSchema;
  }, []);

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props == null) {
      setFormData(initData);
      return;
    }
    const { surface1, surface2, spline }: Params = props.params;

    await initEditDependency(
      [surface1, surface2, spline?.id].filter((id) => id != null),
    );

    setFormData({
      surface1: picker.generatePickObjByPickID(surface1) as pickedFaceData,
      surface2: picker.generatePickObjByPickID(surface2) as pickedFaceData,
      spline:
        spline?.id &&
        (picker.generatePickObjByPickID(spline?.id) as pickedLineData),
      leftBound:
        spline?.leftBound &&
        (picker.generatePickObjByPickID(spline?.leftBound) as pickedVertexData),
      rightBound:
        spline?.rightBound &&
        (picker.generatePickObjByPickID(
          spline?.rightBound,
        ) as pickedVertexData),
    });

    setSolution(props.params.solution);

    return;
  }, [editDxid]);

  const isFormDataValid = () => {
    const basicValid =
      formData.surface1 != null &&
      formData.surface2 != null &&
      formData.spline != null &&
      formData.spline.edgeId != null;

    return basicValid;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) return;

    await execute(false);
    onClose();
  };

  const { initEditDependency, initingEdit, clear, confirmCommand, isLoading } =
    useCommand('cmd-linear-sweep-two-tangency-surfaces', {
      commandName: 'CreateSurface',
      editDxid,
      onClose,
      finishDraw: checkAndFinishDraw,
    });

  const execute = (preview: boolean) => {
    return confirmCommand(
      {
        type: 'LinearSweep',
        a: {
          mode: 'TwoTangencySurfaces',
          surface1: formData.surface1.meshId,
          surface2: formData.surface2.meshId,
          spline: {
            id: formData.spline.edgeId,
            leftBound: formData.leftBound?.vertexId,
            rightBound: formData.rightBound?.vertexId,
          },
          solution,
        } as Params,
      },
      preview,
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      setSolution(0);
      setSolutionNum(0);
      return;
    }

    const { nsolution } = await execute(true);

    setSolutionNum(nsolution);
  };

  const finalFormData = useMemo(
    () => ({
      ...formData,
      solution: [solution, solutionNum],
    }),
    [formData, solution, solutionNum],
  );

  useAsyncEffect(preview, [solution]);

  return (
    <NonDialogPickableCommandForm
      disabled={initingEdit}
      onCancel={onClose}
      schema={schema}
      submitLoading={isLoading}
      formData={finalFormData}
      onChange={(v) => {
        setFormData(v);
        setSolution(v.solution[0]);
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      extraUiSchema={{
        surface1: {
          'ui:autofocus': true,
          'ui:placeholder': '请输入参考曲面1',
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
        surface2: {
          'ui:placeholder': '请输入参考曲面2',
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
        spline: {
          'ui:placeholder': '脊线',
        },
        leftBound: {
          'ui:placeholder': '边界1(选填)',
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
        rightBound: {
          'ui:placeholder': '边界2(选填)',
          'ui:options': {
            allowInfinitePlane: true,
          },
        },
        solution: {
          'ui:widget': MultiSolutionWidget,
        },
      }}
      isFormDataValid={isFormDataValid()}
    />
  );
}
